Maximum binary tree II

Time: O(H); Space: O(1); medium

We are given the root node of a maximum tree: a tree where every node has a value greater than any other value in its subtree.

Just as in the previous problem, the given tree was constructed from an list A (root = Construct(A)) recursively with the following Construct(A) routine:

  • If A is empty, return null.

  • Otherwise, let A[i] be the largest element of A. Create a root node with value A[i].

  • The left child of root will be Construct([A[0], A[1], …, A[i-1]])

  • The right child of root will be Construct([A[i+1], A[i+2], …, A[A.length - 1]])

  • Return root.

Note that we were not given A directly, only a root node root = Construct(A).

Suppose B is a copy of A with the value val appended to it. It is guaranteed that B has unique values.

Return Construct(B).

Example 1:

Input: root = {TreeNode} [4,1,3,null,null,2], val = 5

Output: {TreeNode} [5,4,null,1,3,null,null,2]

Explanation:

  • A = [1,4,2,3], B = [1,4,2,3,5]

Example 2:

Input: root = {TreeNode} [5,2,4,null,1], val = 3

Output: {TreeNode} [5,2,4,null,1,null,3]

Explanation:

  • A = [2,1,5,4], B = [2,1,5,4,3]

Example 3:

Input: root = {TreeNode} [5,2,3,null,1], val = 4

Output: {TreeNode} [5,2,4,null,1,3]

Explanation:

  • A = [2,1,5,3], B = [2,1,5,3,4]

Constraints:

  • 1 <= len(B) <= 100

[1]:
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

Auxiliary Tools

[2]:
from graphviz import Graph

class TreeTasks(object):
    def visualize_tree(self, tree):
        def add_nodes_edges(tree, dot=None):
            # Create Graph (not Digraph) object
            if dot is None:
                dot = Graph()
                dot.node(name=str(tree), label=str(tree.val))
            # Add nodes
            if tree.left:
                dot.node(name=str(tree.left), label="."+str(tree.left.val))
                dot.edge(str(tree), str(tree.left))
                dot = add_nodes_edges(tree.left, dot=dot)
            if tree.right:
                dot.node(name=str(tree.right), label=str(tree.right.val)+".")
                dot.edge(str(tree), str(tree.right))
                dot = add_nodes_edges(tree.right, dot=dot)
            return dot
        # Add nodes recursively and create a list of edges
        dot = add_nodes_edges(tree)
        # Visualize the graph
        display(dot)
        return dot
[3]:
class Solution1(object):
    """
    Time: O(H)
    Space: O(1)
    """
    def insertIntoMaxTree(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """
        if not root:
            return TreeNode(val)

        if val > root.val:
            node = TreeNode(val)
            node.left = root
            return node

        curr = root
        while curr.right and curr.right.val > val:
            curr = curr.right
        node = TreeNode(val)
        curr.right, node.left = node, curr.right
        return root


[4]:
s = Solution1()

root = TreeNode(4)
root.left, root.right = TreeNode(1), TreeNode(3)
root.right.left = TreeNode(2)
val = 5
tree = s.insertIntoMaxTree(root, val)
t = TreeTasks()
dot = t.visualize_tree(tree)
../../_images/topics_tree_0998_maximum_binary_tree_ii_[O(H),O(1),med]_5_0.svg
[5]:
root = TreeNode(5)
root.left, root.right = TreeNode(2), TreeNode(4)
root.left.right = TreeNode(1)
val = 3
tree = s.insertIntoMaxTree(root, val)
t = TreeTasks()
dot = t.visualize_tree(tree)
../../_images/topics_tree_0998_maximum_binary_tree_ii_[O(H),O(1),med]_6_0.svg
[6]:
root = TreeNode(5)
root.left, root.right = TreeNode(2), TreeNode(3)
root.left.right = TreeNode(1)
val = 4
tree = s.insertIntoMaxTree(root, val)
t = TreeTasks()
dot = t.visualize_tree(tree)
../../_images/topics_tree_0998_maximum_binary_tree_ii_[O(H),O(1),med]_7_0.svg